<?php if(!defined('CALL')) exit('No direct script access allowed');

include_once('lib/mysql.class.php');
include_once('cfg/cfg.php');

class mCity
{
	public $id = 0;
	public $props = null;
	
	public function __construct($id = null)
	{
		global $dburl, $def_encoding;
		MySQL::$url = $dburl;
		MySQL::$encoding = $def_encoding;
		self::$db = MySQL::getInstance();
		
		$this->id = $id;
		$this->get_props();
	}
	
	public function get_props()
	{
		$this->props = null;
		
		if($this->id == null) return;
		
		$sql =
			"SELECT c.id, c.region_id, r.country_id, c.name city, r.name region, n.name country, c.population ".
			  "FROM cities c, regions r, countries n ".
			 "WHERE c.region_id = r.id AND n.id = r.country_id ".
			   "ANd c.id = ".$this->id;
				
		if(LOG_SQL)
			Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, $sql);

		$res = self::$db->query($sql);
		if(self::$db->num_rows($res) > 0)
		{
			$row = self::$db->fetch_assoc($res);
			$this->props = $row;
		}
		self::$db->free_result($res);
	}
	
	public function get_countries()
	{
		$rows = array();
		$sql = "SELECT id, name FROM countries";
				
		if(LOG_SQL)
			Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, $sql);

		$res = self::$db->query($sql);
		while($row = self::$db->fetch_assoc($res))
			$rows[] = $row;
			
		self::$db->free_result($res);
		return $rows;
	}
	
	public function get_regions($country_id)
	{
		$rows = array();
		$sql = "SELECT id, name FROM regions WHERE country_id = ".$country_id;
				
		if(LOG_SQL)
			Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, $sql);

		$res = self::$db->query($sql);
		while($row = self::$db->fetch_assoc($res))
			$rows[] = $row;
			
		self::$db->free_result($res);
		return $rows;
	}
	
	public function get_cities($region_id)
	{
		$rows = array();
		$sql = "SELECT id, name FROM cities WHERE region_id = ".$region_id." ORDER BY categ, name";
				
		if(LOG_SQL)
			Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, $sql);

		$res = self::$db->query($sql);
		while($row = self::$db->fetch_assoc($res))
			$rows[] = $row;
			
		self::$db->free_result($res);
		return $rows;
	}
	
	private static $db = null;

}